﻿// GlobalConsoleCapture.cs
using System;
using System.IO;
using System.Text;
using System.Threading;

namespace MultiDAQ_Analysis.Util
{
    /// <summary>
    /// 全局控制台捕获器 - 输出到日志文件
    /// </summary>
    public static class GlobalConsoleCapture
    {
        private static ConsoleTextWriter consoleWriter;
        private static bool isInitialized = false;

        /// <summary>
        /// 初始化控制台捕获 - 只需调用一次
        /// </summary>
        /// <param name="logFilePath">日志文件路径</param>
        public static void Initialize(string logFilePath)
        {
            if (isInitialized) return;

            consoleWriter = new ConsoleTextWriter(logFilePath);
            Console.SetOut(consoleWriter);
            isInitialized = true;

            // 测试输出
            Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 全局控制台捕获已启用，日志文件: {logFilePath}");
        }

        /// <summary>
        /// 停止捕获，恢复原始控制台并关闭文件
        /// </summary>
        public static void Stop()
        {
            if (consoleWriter != null)
            {
                Console.SetOut(consoleWriter.OriginalOut);
                consoleWriter.CloseFile();
                consoleWriter = null;
                isInitialized = false;
            }
        }

        /// <summary>
        /// 清空显示内容（对于文件输出，此方法无效）
        /// </summary>
        public static void Clear()
        {
            // 文件输出不支持清空，此方法保留为空
        }
    }

    /// <summary>
    /// 自定义的 TextWriter，用于重定向控制台输出到文件
    /// </summary>
    internal class ConsoleTextWriter : TextWriter
    {
        private readonly string logFilePath;
        private StreamWriter fileWriter;
        private readonly object lockObject = new object();
        public readonly TextWriter OriginalOut;

        public ConsoleTextWriter(string filePath)
        {
            logFilePath = filePath;
            OriginalOut = Console.Out;

            // 确保目录存在
            string directory = Path.GetDirectoryName(filePath);
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // 初始化文件写入器
            fileWriter = new StreamWriter(filePath, true, Encoding.UTF8)
            {
                AutoFlush = true
            };
        }

        public override Encoding Encoding => Encoding.UTF8;

        public override void Write(char value)
        {
            WriteToFile(value.ToString());
            OriginalOut.Write(value);
        }

        public override void Write(string value)
        {
            WriteToFile(value);
            OriginalOut.Write(value);
        }

        public override void WriteLine(string value)
        {
            string formattedLine = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {value}";
            WriteToFile(formattedLine);
            OriginalOut.WriteLine(value);
        }

        public override void WriteLine()
        {
            WriteToFile("");
            OriginalOut.WriteLine();
        }

        private void WriteToFile(string text)
        {
            lock (lockObject)
            {
                try
                {
                    if (fileWriter != null)
                    {
                        fileWriter.WriteLine(text);
                    }
                }
                catch (Exception ex)
                {
                    // 如果文件写入失败，回退到原始控制台
                    OriginalOut?.WriteLine($"日志写入失败: {ex.Message}");
                }
            }
        }

        public void CloseFile()
        {
            lock (lockObject)
            {
                if (fileWriter != null)
                {
                    fileWriter.Close();
                    fileWriter.Dispose();
                    fileWriter = null;
                }
            }
        }
    }
}